package main

import (
	"flag"
	"gitee.com/sunny-zhangqiang/zcache/service"
	"gitee.com/sunny-zhangqiang/zcache/service/forward"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/sunny-zhangqiang/zcache/cache"
	"gitee.com/sunny-zhangqiang/zcache/cache/fusion"
	"gitee.com/sunny-zhangqiang/zcache/comm/logger"
	"gitee.com/sunny-zhangqiang/zcache/config"
	"gitee.com/sunny-zhangqiang/zcache/config/domain"
)

var (
	help       = flag.Bool("h", false, "to show help")
	serverConf = flag.String("c", "/opt/zcache/conf/server.conf", "server conf configuration")
	clean      = flag.Bool("clean", false, "clean disk cache")
)

func quit() {
	// 先关闭http server
	service.CloseService()
	// 再关闭存储存储引擎
	cache.Cache.Close()
}

func main() {
	flag.Parse()

	if *help {
		flag.PrintDefaults()
		return
	}

	err := config.LoadServerConf(*serverConf)
	if err != nil {
		logger.Error("load server conf failed, err: %v", err)
		os.Exit(1)
		return
	}

	err = domain.Init(config.ServerConf.IncludesDomains, 0)
	if err != nil {
		logger.Error("init domains failed, err: %v", err)
		os.Exit(1)
		return
	}

	c, err := fusion.Open(config.ServerConf.Cache, *clean)
	if err != nil {
		logger.Error("open fusion cache failed, err: %v", err)
		os.Exit(2)
		return
	}

	cache.Cache = c

	// 必须在StartService之前开启transport
	forward.InitTransport(config.ServerConf)

	service.StartService(config.ServerConf)

	quitNotify := make(chan os.Signal)
	signal.Notify(quitNotify, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)

	for {
		select {
		case <-quitNotify:
			quit()
			return
		}
	}
}
